/**
 *    @file       timer.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/13/2014 09:39:53 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#include "timer.h"
#include "server.h"

timer::timer()
{

}

timer::~timer()
{

}

bf_int_t timer::add_timer(interval_timer &itimer)
{
	if (itimer.m_cyclenum == 0)
	{
		return BF_OK;
	}
	itimer.m_last_time = server::get()->get_time();
	m_interval_timers.push_back(itimer);
	return BF_OK;
}

bf_int_t timer::add_timer(point_timer &ptimer)
{
	m_point_timers.push_back(ptimer);
	return BF_OK;
}

bf_int_t timer::check_interval_timer(bf_time_t curtime, std::list<common_timer> &itimers)
{
	std::list<interval_timer>::iterator itr = m_interval_timers.begin();
	std::list<interval_timer>::iterator itr_tmp;
	for (; itr != m_interval_timers.end();)
	{
		itr_tmp = itr ++;
		if (curtime - itr_tmp->m_last_time <= itr_tmp->m_interval) continue;
		itimers.push_back(*itr_tmp);

		itr_tmp->m_last_time += itr_tmp->m_interval;
		if (itr_tmp->m_cyclenum < 0) continue;
		itr_tmp->m_cyclenum --;
		if (itr_tmp->m_cyclenum <= 0) m_interval_timers.erase(itr_tmp);
	}
	return BF_OK;
}

bf_int_t timer::check_point_timer(bf_tm_t &curtime, std::list<common_timer> &ptimers)
{
	std::list<point_timer>::iterator itr = m_point_timers.begin();
	std::list<point_timer>::iterator itr_tmp;
	for (; itr != m_point_timers.end();)
	{
		itr_tmp = itr ++;
		if (itr_tmp->m_year >= 0 && itr_tmp->m_year != curtime.m_year) continue;
		if (itr_tmp->m_mon >= 0 && itr_tmp->m_mon != curtime.m_month) continue;
		if (itr_tmp->m_day >= 0 && itr_tmp->m_day != curtime.m_day) continue;
		if (itr_tmp->m_hour >= 0 && itr_tmp->m_hour != curtime.m_hour) continue;
		if (itr_tmp->m_min >= 0 && itr_tmp->m_min != curtime.m_min) continue;
		if (itr_tmp->m_sec >= 0 && itr_tmp->m_min != curtime.m_sec) continue;
		ptimers.push_back(*itr_tmp);
	}
	return BF_OK;
}

bf_int_t timer::add_timer(workthread *thread, interval_timer &itimer)
{
	itimer.m_src_thd_type = thread->get_thd_type();
	itimer.m_src_thd_index = thread->get_thd_index();

	simplemsgbody<interval_timer> *body = new simplemsgbody<interval_timer>(itimer);
	thread->send_msg(THD_TYPE_TIMER, 0, 0, MSG_TYPE_ADD_ITIMER, body);
	return BF_OK;
}

bf_int_t timer::add_timer(workthread *thread, point_timer &ptimer)
{
	ptimer.m_src_thd_type = thread->get_thd_type();
	ptimer.m_src_thd_index = thread->get_thd_index();

	simplemsgbody<point_timer> *body = new simplemsgbody<point_timer>(ptimer);
	thread->send_msg(THD_TYPE_TIMER, 0, 0, MSG_TYPE_ADD_PTIMER, body);
	return BF_OK;
}

